package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CostomException;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.ApAuthor;
import com.heima.model.common.pojos.ApUser;
import com.heima.model.common.pojos.ApUserRealname;
import com.heima.model.common.pojos.WmUser;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.micrometer.core.instrument.util.StringUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Constants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional //事务
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //判断参数
        if(dto==null){

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断分页数据
        dto.checkParam();
        //执行查询条件
        LambdaQueryWrapper<ApUserRealname>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //判断参数
        if(dto.getStatus()!=null){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //设置分页条件
        Page page = new Page(dto.getPage(),dto.getSize());
        //执行方法查询
        IPage result =page(page,lambdaQueryWrapper);
        //封装查询结果
        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(), (int) result.getTotal());

        responseResult.setData(result.getRecords());
        //返回数据
        return responseResult;
    }


    //校验用户申请，1.如果成功修改用户状态并且创建自媒体对象和作者
    //2.如果失败则修改用户状态和失败原因
    @GlobalTransactional//解决分布式事务注解
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
            //判断参数
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //创建申请用户对象，便于修改信息
        ApUserRealname realname = new ApUserRealname();
        //用户ID
        realname.setId(dto.getId());
        //修改用户状态
        realname.setStatus(status);
        //如果信息存在则修改校验保存失败信息
        if(StringUtils.isNotBlank(dto.getMsg())){
            realname.setReason(dto.getMsg());
        }
        //修改信息
        updateById(realname);
        //通过状态判断是否校验成功
        if(status.equals(AdminConstants.PASS_AUTH)){
            //验证成功，创建自媒体用户和作者★★★
            ResponseResult responseResult = createWmUserAndAuthor(dto);
            if(responseResult!=null){
                return responseResult;
            }
        }
        //定义异常测试事务
       // int a =1/0;

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    //创建自媒体接口
    WmUserFeign wmUserFeign;

    @Autowired
    //用户接口
    ApUserMapper  apUserMapper;

    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //根据ID查询用户的信息 并且信息全部保存到自媒体用户中
        ApUserRealname byId = getById(dto.getId());
        ApUser apUser = apUserMapper.selectById(byId.getUserId());

        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = wmUserFeign.findWmuserByName(apUser.getName());
        //值有效则全部存到自媒体表中
       if(wmUser==null) {
           wmUser= new WmUser();
           wmUser.setApUserId(apUser.getId());
           wmUser.setCreatedTime(new Date());
           wmUser.setPassword(apUser.getPassword());
           wmUser.setName(apUser.getName());
           wmUser.setSalt(apUser.getSalt());
           wmUser.setPhone(apUser.getPhone());
           wmUser.setStatus(Integer.valueOf(AdminConstants.PASS_AUTH));
           ResponseResult responseResult = wmUserFeign.save(wmUser);
           //判断分模块如果有异常，则返回的结果为null
           if(responseResult.getCode()!=0){
               //此时分模块有异常，抛出从而让主线程回滚事务
               throw new CostomException(ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAIL));

           }

       }
        //创建作者★★★
        creatAuthor(apUser);
        //更改用户的标识
        apUser.setFlag(AdminConstants.USER_TYPE);
        apUserMapper.updateById(apUser);
        return null;
    }
    @Autowired
    //创建作者接口
    ApAuthorFeign apAuthorFeign;
    private void creatAuthor(ApUser apUser) {
        //通过用户的ID去查询作者表，并进行判断
        ApAuthor apAuthor = apAuthorFeign.findApAuthorById(apUser.getId());

        if(apAuthor==null){
            apAuthor=new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(apUser.getName());
            apAuthor.setUserId(apUser.getId());
            apAuthor.setType(AdminConstants.AUTH_TYPE);
            ResponseResult responseResult = apAuthorFeign.save(apAuthor);

            //判断分模块如果有异常，则返回的结果为null
            if(responseResult.getCode()!=0){
                //此时分模块有异常，抛出从而让主线程回滚事务
                throw new CostomException(ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAIL));

            }
        }
    }
}
